﻿using System;
using System.Collections.Generic;
using System.IO;
using UpdaterForm.Utils;

namespace UpdaterForm.CustomTreeView
{
    public class FileNode : ATreeNode
    {
        private readonly FileInfo _file;
        private readonly String _target;

        public FileNode(FileInfo file, String Target)
        {
            Children = new List<ATreeNode>();
            _file = file;
            _target = Target;
            Name = file.Name;
        }

        private AppData _appData
        {
            get { return Settings.Instance.Data.GetByInstallPath(_target); }
        }


        private bool CheckInLogs()
        {
            var updateName = Root.Name;
            var log = _appData.History.GetLog(updateName);
            if (log != null)
            {
                var logFiles = log.TransferedFiles;
                if (logFiles.Count > 0)
                    return logFiles.Contains(_file.FullName);
            }

            return false;
        }

        public override void Initialize()
        {
            IsTransfered = CheckInLogs();
        }


        public override void Apply(bool custom)
        {
            if (_appData == null)
                return;

            if (custom)
            {
                if (IsChecked ?? false)
                    TransferFile();
            }
            else
                TransferFile();
        }

        private void TransferFile()
        {
            FileUtil.MoveFile(_target, _file);

            IsTransfered = true;

            var updateDate = Root.Name;
            var log = _appData.History.GetLog(updateDate);
            if (log == null) 
                return;
            var logFiles = log.TransferedFiles;
            if (!logFiles.Contains(_file.FullName))
                logFiles.Add(_file.FullName);
        }
    }
}